package com.wmh.baseservice.admin.controller;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wmh.baseservice.common.annotation.parameterverify.ParameterVerify;
import com.wmh.baseservice.common.ex.ServiceException;
import com.wmh.baseservice.common.utils.CommUtil;
import com.wmh.baseservice.common.utils.page.pojo.PageInfo;
import com.wmh.baseservice.common.utils.page.pojo.PageResult;
import com.wmh.baseservice.common.utils.page.pojo.SortWay;
import com.wmh.baseservice.common.utils.page.util.PageUtil;
import com.wmh.baseservice.common.utils.returnbody.ResultCodeInfo;
import com.wmh.baseservice.common.utils.returnbody.ReturnBody;
import com.wmh.baseservice.merchant.pojo.*;
import com.wmh.baseservice.merchant.service.*;
import com.wmh.baseservice.system.pojo.SysCategory;
import com.wmh.baseservice.system.service.SysCategoryService;
import com.wmh.baseservice.user.pojo.UsInfo;
import com.wmh.baseservice.user.service.UsInfoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.annotations.ApiIgnore;

import javax.annotation.Resource;
import javax.el.MapELResolver;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@ApiIgnore
@Api(tags = "管理员-加盟商相关功能接口")
@RestController
@RequestMapping("admin/merchantManage")
@RequiresRoles("admin")
public class AdMerchantController {

    @Resource
    private MerchantInfoService merchantInfoService;
    @Resource
    private MerchantVegetablePlotService merchantVegetablePlotService;
    @Resource
    private MerchantVegetableService merchantVegetableService;
    @Resource
    private SysCategoryService sysCategoryService;
    @Resource
    private MerchantApplyService merchantApplyService;
    @Resource
    private MerchantBankCardService merchantBankCardService;
    @Resource
    private MerchantPlotRegionService merchantPlotRegionService;
    @Resource
    private UsInfoService usInfoService;
    @Resource
    private HttpServletRequest request;


    @ApiOperation("商家列表")
    @PostMapping("merchantList")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataTypeClass = Long.class, name = "id", value = "id", required = false),
    })
    public String merchantList(PageInfo pageInfo, Long id, String name) {
        pageInfo.setTimeScreen("create_time");
        pageInfo.setDefaultSort("create_time", SortWay.DESC);
        //执行分页辅助工具
        PageResult<MerchantInfo> pageResult = new PageUtil<MerchantInfo>(pageInfo).startPage((page, queryWrapper) -> {
            if (CommUtil.checkNull(id)) {
                queryWrapper.eq(MerchantInfo.ID, id);
            }
            if (CommUtil.checkNull(name)) {
                queryWrapper.like(MerchantInfo.NAME, name);
            }
            queryWrapper.select(MerchantInfo.getFields(MerchantInfo.SALT, MerchantInfo.PASSWORD));
            merchantInfoService.page(page, queryWrapper);
        });
        return ReturnBody.success(pageResult);
    }

    @ApiOperation("冻结/解冻")
    @PostMapping("updateStatus")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataTypeClass = Long.class, name = "id", value = "id", required = false),
    })
    public String updateStatus(Long id) {
        MerchantInfo merchantInfo = merchantInfoService.getByIdForUpdate(id);
        if (!CommUtil.checkNull(merchantInfo)) {
            return ReturnBody.error(ResultCodeInfo.PARAM_ERROR);
        }
        merchantInfo.setStatus(merchantInfo.getStatus() == 1 ? 0 : 1);
        if (!merchantInfoService.updateById(merchantInfo)) {
            return ReturnBody.error(ResultCodeInfo.SERVICE_EXCEPTION);
        }
        return ReturnBody.success();
    }

    @ApiOperation("土地列表")
    @PostMapping("plotList")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataTypeClass = Long.class, name = "id", value = "id", required = false),
    })
    public String plotList(PageInfo pageInfo, String name, Long id, Long merchantId) {
        Map<String, Object> map = new HashMap<>(16);
        PageResult<MerchantVegetablePlot> pageResult = new PageResult<>();
        Page<MerchantVegetablePlot> vegetablePagePlot = new Page<>(pageInfo.getPageNo(), pageInfo.getPageSize());
        if (CommUtil.checkNull(name)) {
            map.put("name", name);
        }
        if (CommUtil.checkNull(id)) {
            map.put("id", id);
        }
        if (CommUtil.checkNull(merchantId)) {
            MerchantInfo merchantInfo = merchantInfoService.getByIdForUpdate(merchantId);
            if (CommUtil.checkNull(merchantInfo)) {
                if (merchantInfo.getParentId() != -1) {
                    MerchantInfo parentMerchantInfo = merchantInfoService.getOneForUpdate(new QueryWrapper<MerchantInfo>().eq(MerchantInfo.US_ID, merchantInfo.getParentId()));
                    merchantId = parentMerchantInfo.getId();
                }
            }
            map.put("merchantId", merchantId);
        }
        IPage<MerchantVegetablePlot> vegetableIPage = merchantVegetablePlotService.getVegetablePlotList(vegetablePagePlot, map);
        pageResult.setPageSize(vegetableIPage.getSize()).setPageNo(vegetableIPage.getCurrent()).setPages(vegetableIPage.getPages()).
                setTotal(vegetableIPage.getTotal());
        pageResult.setList(vegetableIPage.getRecords());
        return ReturnBody.success(pageResult);
    }

    @ApiOperation("蔬菜列表")
    @PostMapping("vegetableList")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataTypeClass = Long.class, name = "id", value = "id", required = false),
    })
    public String vegetableList(PageInfo pageInfo, Long categoryId, Long merchantId, String title, Long plotId, Integer type) {
        Map<String, Object> map = new HashMap<>(16);
        PageResult<MerchantVegetable> pageResult = new PageResult<>();
        Page<MerchantVegetable> vegetablePage = new Page<>(pageInfo.getPageNo(), pageInfo.getPageSize());
        map.put("selectType", "admin");
        if (CommUtil.checkNull(merchantId)) {
            map.put("merchantId", merchantId);
        }
        if (CommUtil.checkNull(categoryId)) {
            map.put("categoryId", categoryId);
        }
        if (CommUtil.checkNull(type)) {
            map.put("type", type);
        }
        if (CommUtil.checkNull(title)) {
            map.put("title", title);
        }
        if (CommUtil.checkNull(plotId)) {
            map.put("plotId", plotId);
        }
        IPage<MerchantVegetable> vegetableIPage = merchantVegetableService.getVegetableList(vegetablePage, map);
        pageResult.setPageSize(vegetableIPage.getSize()).setPageNo(vegetableIPage.getCurrent()).setPages(vegetableIPage.getPages()).
                setTotal(vegetableIPage.getTotal());
        pageResult.setList(vegetableIPage.getRecords());
        return ReturnBody.success(pageResult);
    }

    @ApiOperation("上下架")
    @PostMapping("upOrDown")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataTypeClass = Long.class, name = "id", value = "id", required = false),
    })
    public String upOrDown(Long id) {
        MerchantVegetable merchantVegetable = merchantVegetableService.getByIdForUpdate(id);
        if (!CommUtil.checkNull(merchantVegetable)) {
            return ReturnBody.error(ResultCodeInfo.PARAM_ERROR);
        }
        merchantVegetable.setStatus(merchantVegetable.getStatus() == -1 ? 0 : -1);
        if (!merchantVegetableService.updateById(merchantVegetable)) {
            return ReturnBody.error(ResultCodeInfo.SERVICE_EXCEPTION);
        }
        return ReturnBody.success();
    }

    @ApiOperation("提现审核列表")
    @PostMapping("auditList")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataTypeClass = Long.class, name = "id", value = "id", required = false),
    })
    public String auditList(PageInfo pageInfo) {
        pageInfo.setTimeScreen("create_time");
        pageInfo.setDefaultSort("create_time", SortWay.DESC);
        //执行分页辅助工具
        PageResult<MerchantApply> pageResult = new PageUtil<MerchantApply>(pageInfo).startPage((page, queryWrapper) -> {
            merchantApplyService.page(page, queryWrapper);
        });
        pageResult.getList().forEach(item -> {
            UsInfo usInfo = merchantApplyService.getUsInfo(item.getMerchantId());
            if (!CommUtil.checkNull(usInfo)) {
                throw new ServiceException("提现审核列表：获取用户信息错误");
            }
            item.setNick(usInfo.getNick());
            item.setAvatar(usInfo.getAvatar());
        });
        return ReturnBody.success(pageResult);
    }

    @ApiOperation("提现申请详情")
    @PostMapping("auditDetail")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataTypeClass = Long.class, name = "id", value = "id", required = false),
    })
    @ParameterVerify(notNull = "id")
    public String auditDetail(Long id) {
        JSONObject object = new JSONObject(true);
        MerchantApply merchantApply = merchantApplyService.getByIdForUpdate(id);
        if (!CommUtil.checkNull(merchantApply)) {
            return ReturnBody.error(ResultCodeInfo.PARAM_ERROR);
        }
        //银行卡信息
        MerchantBankCard card = merchantBankCardService.getByIdForUpdate(merchantApply.getBankCardId());
        //用户信息
        MerchantInfo merchantInfo = merchantInfoService.getByIdForUpdate(merchantApply.getMerchantId());
        UsInfo usInfo = usInfoService.getByIdForUpdate(merchantInfo.getUsId());
        object.put("apply", merchantApply);
        object.put("card", card);
        object.put("nick", usInfo.getNick());
        object.put("avatar", usInfo.getAvatar());
        object.put("balance", merchantInfo.getBalance());
        return ReturnBody.success(object);
    }

    @ApiOperation("审核")
    @PostMapping("audit")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataTypeClass = Long.class, name = "id", value = "id", required = false),
    })
    @ParameterVerify(notNull = {"id", "status"})
    public String audit(Long id, Integer status, String refuseReason) {
        Long adId = (Long) request.getAttribute("id");
        MerchantApply merchantApply = merchantApplyService.getByIdForUpdate(id);
        if (!CommUtil.checkNull(merchantApply)) {
            return ReturnBody.error(ResultCodeInfo.PARAM_ERROR);
        }
        if (merchantApply.getStatus() != 0) {
            return ReturnBody.error("该工单已审核过，请不要重复操作");
        }
        merchantApply.setStatus(status);
        if (status == -1) {
            if (!CommUtil.checkNull(refuseReason)) {
                return ReturnBody.error("拒绝原因不能为空");
            }
            merchantApply.setRefuseReason(refuseReason);
        }
        merchantApply.setAuditId(adId);
        merchantApply.setAuditTime(new Date());
        merchantApplyService.audit(merchantApply);
        return ReturnBody.success();
    }

    @ApiOperation("区域列表")
    @PostMapping("regionList")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataTypeClass = Long.class, name = "id", value = "id", required = false),
    })
    public String regionList(PageInfo pageInfo, Long merchantId, Long plotId, String plotName, String name) {
        Map<String, Object> map = new HashMap<>(16);
        PageResult<MerchantPlotRegion> pageResult = new PageResult<>();
        if (CommUtil.checkNull(merchantId)) {
            map.put("merchantId", merchantId);
        }
        if (CommUtil.checkNull(plotId)) {
            map.put("plotId", plotId);
        }
        if (CommUtil.checkNull(plotName)) {
            map.put("plotName", plotName);
        }
        if (CommUtil.checkNull(name)) {
            map.put("name", name);
        }
        Page<Object> vegetablePage = new Page<>(pageInfo.getPageNo(), pageInfo.getPageSize());
        IPage<MerchantPlotRegion> merchantPlotRegionIPage = merchantPlotRegionService.getList(vegetablePage, map);
        pageResult.setPageSize(merchantPlotRegionIPage.getSize()).setPageNo(merchantPlotRegionIPage.getCurrent()).setPages(merchantPlotRegionIPage.getPages()).
                setTotal(merchantPlotRegionIPage.getTotal());
        pageResult.setList(merchantPlotRegionIPage.getRecords());
        return ReturnBody.success(pageResult);
    }

    @ApiOperation("上下架")
    @PostMapping("updateRegionStatus")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataTypeClass = Long.class, name = "id", value = "id", required = false),
    })
    public String updateRegionStatus(Long id) {
        MerchantPlotRegion merchantPlotRegion = merchantPlotRegionService.getByIdForUpdate(id);
        if (!CommUtil.checkNull(merchantPlotRegion)) {
            return ReturnBody.error(ResultCodeInfo.PARAM_ERROR);
        }
        merchantPlotRegion.setStatus(merchantPlotRegion.getStatus() == -1 ? 0 : -1);
        if (!merchantPlotRegionService.updateById(merchantPlotRegion)) {
            return ReturnBody.error(ResultCodeInfo.SERVICE_EXCEPTION);
        }
        return ReturnBody.success();
    }
}
